package org.dbutils.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;
import org.dbutils.dao.HandlerDao;
import org.dbutils.entity.Staff;
import org.dbutils.util.DruidUtil;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class HandlerDaoImpI implements HandlerDao {

    // 第二：定义 DbUtils 工具类的 SQL 执行器
    QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());

    public Map<String,Object> selectId(int id){
        String sql="select * from staffs where id=?";
        try {
            return qr.query(sql,new MapHandler(),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Map<String,Object>> selectPage(){
        String sql="select * from staffs";
        try {
            return qr.query(sql,new MapListHandler());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Staff selectById(int id){
        String sql="select * from staffs where id=?";
        BeanHandler<Staff> handler=new BeanHandler<>(Staff.class);
        try {
            return qr.query(sql,handler,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Staff> selectByPage(){
        String sql="select * from staffs";
        BeanListHandler<Staff> handler=new BeanListHandler<>(Staff.class);
        try {
            return qr.query(sql,handler);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String selectByName(int id) {
        String sql="select name from staffs where id=?";
        try {
            return qr.query(sql,new ScalarHandler<>(),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Long selectrow() {
        String sql="select count(*) from staffs";
        try {
            return qr.query(sql,new ScalarHandler<>());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> selectAllName() {
        String sql="select Name from staffs";
        try {
            return qr.query(sql,new ColumnListHandler<>());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object[] selectOid(int id) {
        String sql="select * from staffs where id=?";
        try {
            return qr.query(sql,new ArrayHandler(),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Object[]> selectOAll() {
        String sql="select * from staffs";
        try {
            return qr.query(sql,new ArrayListHandler());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
